package com.renfei.cameralibrary.widget;

import android.view.View;
import android.view.ViewGroup;

import com.renfei.cameralibrary.R;

import java.lang.ref.WeakReference;

/**
 *
 */
public class PreviewMeasureListener implements CameraMeasureFrameLayout.OnMeasureListener {
    private final WeakReference<CameraMeasureFrameLayout> weakReference;


    public PreviewMeasureListener(CameraMeasureFrameLayout frameLayout) {
        this.weakReference = new WeakReference<>(frameLayout);
    }

    @Override
    public void onMeasure(int width, int height) {
        if (null != weakReference.get()) {
            calculatePreviewLayout(weakReference.get(), width, height);
            weakReference.get().setOnMeasureListener(null);
        }
    }

    /**
     * 计算预览布局大小
     *
     * @param preview
     * @param widthPixel
     * @param heightPixel
     */
    private void calculatePreviewLayout(View preview, int widthPixel, int heightPixel) {
        float height = preview.getResources().getDimension(R.dimen.camera_tab_height);
        if (widthPixel * 1.0f / heightPixel > 9f / 16f) {
            widthPixel = (int) (heightPixel * (9f / 16f));
            ViewGroup.LayoutParams params = preview.getLayoutParams();
            params.width = widthPixel;
            params.height = heightPixel;
            preview.setLayoutParams(params);
        } else if (widthPixel * 1.0f / (heightPixel - height) < 9f / 16f) {
            ViewGroup.LayoutParams params = preview.getLayoutParams();
            params.width = widthPixel;
            params.height = (int) (heightPixel - height);
            preview.setLayoutParams(params);
        }
        preview.requestLayout();
    }
}
